package com.bsj.sipgateway.sip.transmit.response.impl;

import com.bsj.power.common.def.entity.gb28181.Device;
import com.bsj.power.common.def.entity.log.CmdLog;
import com.bsj.power.common.def.enums.CmdLogEnum;
import com.bsj.power.common.mapper.CmdLogMapper;
import com.bsj.power.common.mapper.DeviceMapper;
import com.bsj.sipgateway.config.SipConfig;
import com.bsj.sipgateway.sip.SipLayer;
import com.bsj.sipgateway.sip.session.CallIdManager;
import com.bsj.sipgateway.sip.transmit.response.ISIPResponseProcessor;
import gov.nist.javax.sip.header.CallID;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.sip.ResponseEvent;
import javax.sip.message.Response;
import java.util.Date;

/**
 *
 */
@Component
@Slf4j
public class MessageResponseProcessor implements ISIPResponseProcessor {

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private CmdLogMapper cmdLogMapper;

    @Override
    public void process(ResponseEvent evt, SipLayer layer, SipConfig config) {

//        log.info("收到Message响应200");
        // 查询录像列表命令设备回复200OK，这里收到OK只做记录
        Response response = evt.getResponse();
        int statusCode = response.getStatusCode();
        CallID callID = (CallID) response.getHeader(CallID.NAME);
        String deviceId = CallIdManager.getDeviceId(callID.getCallId());
        Device device = deviceMapper.getDeviceByDeviceId(deviceId);
        if (null == device) {
            log.error("收到Invite，查询device为空,{}", deviceId);
            return;
        }
//        ViaHeader viaHeader = (ViaHeader) response.getHeader(ViaHeader.NAME);
//        Command cache = CommandManager.get(deviceId, viaHeader.getBranch());

        CmdLog cmdLog = new CmdLog();
        cmdLog.setDeviceId(device.getDeviceId());
        cmdLog.setDeviceName(device.getNickName());
        String desc = CmdLogEnum.TYPE_RECORD_QUERY.getDesc();
        cmdLog.setType(desc);
        cmdLog.setState(CmdLogEnum.STATE_RECEIVE.getDesc());
        cmdLog.setContent("收到Message响应，statusCode" + statusCode);
        cmdLog.setTime(new Date());
        cmdLogMapper.insert(cmdLog);

    }

}
